<template>
  <div class="flex justify-between">
    <div class="font-bold mb-4">快速选择</div>
    <div class="flex gap-x-2">
      <v-btn variant="outlined" @click="handleClear" size="small">清空</v-btn>

      <v-btn color="primary" @click="handleAdd" size="small">添加</v-btn>
      <v-dialog max-width="500" :loading="pullLoading">
        <template v-slot:activator="{ props: activatorProps }">
          <v-btn v-bind="activatorProps" color="blue-lighten-2" size="small" text="拉取歌单"></v-btn>
        </template>
        <template v-slot:default="{ isActive }">
          <v-card title="拉取歌单">
            <v-card-text>
              <v-text-field type="number" v-model="gedanId" label="请输入歌单ID"></v-text-field>
            </v-card-text>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn text="取消" @click="isActive.value = false"></v-btn>
              <v-btn text="确定" :loading="pullLoading" @click="handlePull(isActive)"></v-btn>
            </v-card-actions>
          </v-card>
        </template>
      </v-dialog>
    </div>
  </div>
  <div>
    <div class="w-full overflow-x-auto opt-custom-scroll min-h-[50px]">
      <ul class="flex items-center flex-row flex-nowrap gap-x-4 py-2">
        <li
          v-for="(item, index) in arrs"
          class="flex items-center justify-between flex-none overflow-hidden gap-x-2 border px-4 py-1 rounded-full select-none"
          :class="{
            '!border-[rgb(var(--v-theme-primary))]': selection === item.payload.value,
            '!border-subtitle text-opacity-80': selection !== item.payload.value,
          }"
          @click.stop="handleSelect(item.payload.value)"
          :key="item.payload.value"
        >
          <span
            class="max-w-[160px] text-nowrap text-ellipsis whitespace-nowrap overflow-hidden"
            :class="{
              'text-[rgb(var(--v-theme-primary))]': selection === item.payload.value,
              'text-subtitle text-opacity-80': selection !== item.payload.value,
            }"
            >{{ item.payload.alingTitle }}</span
          >
          <span @click.stop="handleDel(item)">
            <j-icon size="8" :color="selection === item.payload.value ? '#ffa726' : 'rgba(var(--v-subtitle),0.5)'"
              >MdiClose</j-icon
            ></span
          >
        </li>
      </ul>
    </div>
  </div>
</template>
<script setup>
import config, { messageType } from "@/views/TouYing/config";
import { useModel, watch, ref, inject, toRefs, computed, effect } from "vue";
import { $toast } from "@/utils/utils";
import { gedanController } from "@/api/cloudbase-user-action-log";

const props = defineProps({
  modelValue: { modelValue: { type: Object, default: () => ({}) } },
});
const sgbList = inject("sgbList");
const emit = defineEmits(["update:modelValue", "change"]);
const modelValue = useModel(props, "modelValue", emit);
const { quickOptions } = toRefs(modelValue.value);
const gedanId = ref(null);
const arrs = computed(() => {
  return quickOptions.value
    .filter((item) => Boolean(item.payload))
    .map((options) => {
      let findSgbData;
      if (options.messageType === messageType.GP || options.messageType === messageType.ZM) {
        findSgbData = sgbList.value.find((item) => item._id === options.payload?.value);
      }

      return {
        ...options,
        payload: {
          value: options.payload.value,
          alingTitle:
            options.messageType === messageType.GP || options.messageType === messageType.ZM
              ? `${findSgbData?.xuhao}.${findSgbData?.mulu}` || ""
              : options.payload.value,
        },
      };
    });
});

const selection = computed(() => {
  return props.modelValue?.payload?.value;
});
function handleAdd() {
  if (arrs.value.some((item) => item.payload.value === props.modelValue?.payload?.value)) {
    $toast.warning("已存在");
    return;
  }

  if (!props.modelValue?.payload?.value) {
    return;
  }

  quickOptions.value.push({
    messageType: props.modelValue.messageType,
    payload: props.modelValue.payload,
  });

  emit("change");
}

function handleSelect(value) {
  const findRes = arrs.value.find((item) => item.payload.value === value);
  if (!findRes) {
    $toast.warning("未找到相关项目");
    return;
  }

  // 当前选择的是歌谱类型，且选择的是赞美类型的数据时，不做任何改变。
  if (!(modelValue.value.messageType == messageType.GP && findRes.messageType == messageType.ZM)) {
    modelValue.value.messageType = findRes.messageType;
  }

  modelValue.value.payload = { value: findRes.payload.value };
  emit("change");
}
const pullLoading = ref(false);
async function handlePull(isActive) {
  if (!gedanId.value) {
    $toast.error("请输入歌单ID");
    return;
  }
  pullLoading.value = true;
  try {
    const gedanRes = await gedanController.getGeDanDatailList(gedanId.value);
    console.log(gedanRes);
    if (!Array.isArray(gedanRes.list)) {
      $toast.error("没有找到这个歌单");
      return;
    }
    if (gedanRes.list.length === 0) {
      $toast.error("歌单没有歌曲");
      return;
    }
    const list = gedanRes.list;
    const newList = list.filter(Boolean).map((item) => {
      let [id, type] = item.split("|");
      type = type === "1" ? "JW" : "ZM";
      return {
        messageType: type,
        payload: {
          value: id,
        },
      };
    });

    quickOptions.value = [...quickOptions.value, ...newList];
    emit("change");
    $toast.success("拉取歌单成功");
    isActive.value = false;
  } catch (error) {
    console.log(error);
    $toast.error("拉取歌单失败");
  } finally {
    pullLoading.value = false;
  }
}

function handleDel(data) {
  const { value } = data.payload;

  quickOptions.value = quickOptions.value.filter((item) => item.payload && item.payload.value !== value);

  emit("change");
}

function handleClear() {
  quickOptions.value = [];
  emit("change");
}
</script>
<style scoped>
/* Firefox */
* {
  scrollbar-width: thin;
  scrollbar-color: #ffa726 rgba(255, 255, 255, 0.1);
}

/* Chrome, Edge and Safari */
*::-webkit-scrollbar {
  width: 10px;
  width: 10px;
}
*::-webkit-scrollbar-track {
  border-radius: 5px;
  background-color: transparent;
}

*::-webkit-scrollbar-track:hover {
  background-color: transparent;
}

*::-webkit-scrollbar-track:active {
  background-color: transparent;
}

*::-webkit-scrollbar-thumb {
  border-radius: 5px;
  background-color: #ffa726;
}

*::-webkit-scrollbar-thumb:hover {
  background-color: #e6b209;
}

*::-webkit-scrollbar-thumb:active {
  background-color: #5d3ba3;
}
</style>
